home *** CD-ROM | disk | FTP | other *** search
/ Collection of Tools & Utilities / Collection of Tools and Utilities.iso / archiver / pdtar.zip / GETOPT.C < prev    next >
C/C++ Source or Header  |  1987-08-26  |  2KB  |  64 lines

  1. /* got this off net.sources */
  2. #include <stdio.h>
  3.  
  4. /*
  5.  * get option letter from argument vector
  6.  */
  7. int             opterr = 1,        /* useless, never set or used */
  8.                 optind = 1,        /* index into parent argv vector */
  9.                 optopt;            /* character checked for validity */
  10. char           *optarg;            /* argument associated with option */
  11.  
  12. #define BADCH    (int)'?'
  13. #define EMSG    ""
  14. #define tell(s)    fputs(*nargv,stderr);fputs(s,stderr); \
  15.         fputc(optopt,stderr);fputc('\n',stderr);return(BADCH);
  16.  
  17. getopt(nargc, nargv, ostr)
  18. int             nargc;
  19. char          **nargv, *ostr;
  20. {
  21.     static char    *place = EMSG;        /* option letter processing */
  22.     register char  *oli;        /* option letter list index */
  23.     char           *index();
  24.  
  25.     if (!*place)
  26.     {                            /* update scanning pointer */
  27.         if (optind >= nargc || *(place = nargv[optind]) != '-' || !*++place)
  28.             return (EOF);
  29.         if (*place == '-')
  30.         {                        /* found "--" */
  31.             ++optind;
  32.             return (EOF);
  33.         }
  34.     }                            /* option letter okay? */
  35.     if ((optopt = (int) *place++) == (int) ':' || !(oli = index(ostr, optopt)))
  36.     {
  37.         if (!*place)
  38.             ++optind;
  39.         tell(": illegal option -- ");
  40.     }
  41.     if (*++oli != ':')
  42.     {                            /* don't need argument */
  43.         optarg = NULL;
  44.         if (!*place)
  45.             ++optind;
  46.     }
  47.     else
  48.     {                            /* need an argument */
  49.         if (*place)
  50.             optarg = place;        /* no white space */
  51.         else
  52.         if (nargc <= ++optind)
  53.         {                        /* no arg */
  54.             place = EMSG;
  55.             tell(": option requires an argument -- ");
  56.         }
  57.         else
  58.             optarg = nargv[optind];        /* white space */
  59.         place = EMSG;
  60.         ++optind;
  61.     }
  62.     return (optopt);            /* dump back option letter */
  63. }
  64.